﻿using Microsoft.Extensions.DependencyInjection;
using Modules.System.User;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Entity;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Person.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class PersonCorpContractRepository : Repository<PersonCorpContract, DefaultDbContext>
    {
        private readonly IApplicationContext applicationContext;

        public PersonCorpContractRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
            this.applicationContext = applicationContext;
        }

        public IPagedList<PersonCorpContract> GetPersonCorpContracts(PersonCorpContractQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("a.id")
                .From("person_corp_contract as a");
            sql.InnerJoin("person as b ").On("a.person_id=b.person_id");
            sql.InnerJoin("corp as c").On("a.corp_id=c.corp_id");

            #region 主管单位数据权限

            if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator())
            {
                sql.InnerJoin("project_group_member as m").On("m.corp_id=a.corp_id and m.person_id=a.person_id");
                sql.InnerJoin("project as prj").On("m.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type=@0 ", deptUser.IndustryType);
                if (deptUser.Level == AdministrativeLevel.City)
                    sql.Where("prj.city_code=@0", deptUser.CityCode ?? -1);
                if (deptUser.Level == AdministrativeLevel.Area)
                    sql.Where("prj.area_code=@0", deptUser.AreaCode ?? -1);
            }

            #endregion 主管单位数据权限

            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("c.name Like @0 or b.name like @0", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.StartTime.HasValue)
                sql.Where("a.start_date>@0", query.StartTime.Value.Date);
            if (query.EndTime.HasValue)
                sql.Where("a.end_date>@0", query.EndTime.Value.Date.AddDays(1));
            if (query.ProjectId.HasValue)
                sql.Where("a.project_id=@0", query.ProjectId.Value);
            if (query.CorpIds != null && query.CorpIds.Count() > 0)
                sql.Where("a.corp_id in(@0)", query.CorpIds);
            sql.GroupBy("c.project_id,a.person_id,a.corp_id");
            sql.OrderBy("a.create_date DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        public IEnumerable<PersonCorpContract> GetPersonCorpContractByIdsProjectId(IEnumerable<int> ids, int projectId)
        {
            if (ids == null || ids.Count() == 0)
                return Enumerable.Empty<PersonCorpContract>();
            Sql sql = Sql.Builder;
            sql.Select("a.id").From("person_corp_contract as a")
                .InnerJoin("person as b").On("a.person_id=b.person_id")
                .InnerJoin("corp as c").On("a.corp_id=c.corp_id")
                .InnerJoin("project_group_member as m").On("m.person_id=a.person_id");
            sql.Where("m.project_id=@(0) and a.id in(@1)", projectId, ids);
            return PopulateEntitiesByEntityIds(DbContext.Fetch<int>(sql));
        }

        /// <summary>
        /// 人员是否存在合同
        /// </summary>
        /// <param name="personId"></param>
        /// <param name="projectId"></param>
        /// <param name="corpId"></param>
        /// <returns></returns>
        public bool ExistByProjectIdPersonIdCorpId(int personId, int projectId, int corpId)
        {
            return DbContext.Exists<PersonCorpContract>("person_id=@0 and project_id=@1 and corp_id=@2", personId, projectId, corpId);
        }

        public IEnumerable<PersonCorpContract> GetPersonCorpContractsByPersonIds(IEnumerable<int> personIds)
        {
            if (personIds == null || personIds.Count() == 0)
                return Enumerable.Empty<PersonCorpContract>();

            Sql sql = Sql.Builder;
            sql.Select("a.id")
                .From("person_corp_contract as a");

            #region 主管单位数据权限

            if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator())
            {
                sql.InnerJoin("project as prj").On($"a.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type=@0 ", deptUser.IndustryType);
                if (deptUser.Level == AdministrativeLevel.City)
                    sql.Append($" and prj.city_code={deptUser.CityCode}");
                if (deptUser.Level == AdministrativeLevel.Area)
                    sql.Append($" and prj.area_code={deptUser.AreaCode}");
            }
            sql.Where("person_id IN(@0)", personIds);
            sql.OrderBy("a.create_date desc");

            #endregion 主管单位数据权限

            var ids = DbContext.FetchFirstColumn<int>(sql);
            return PopulateEntitiesByEntityIds(ids);
        }

        //public IEnumerable<PersonCorpContract> GetPersonCorpContractsByCorpIds(IEnumerable<int> corpIds)
        //{
        //    if (corpIds == null || corpIds.Count() == 0)
        //        return Enumerable.Empty<PersonCorpContract>();

        //    Sql sql = Sql.Builder;
        //    sql.Select("id")
        //        .From("person_corp_contract")
        //        .Where("corp_id IN(@0)", corpIds);
        //    sql.OrderBy("create_date desc");
        //    var ids = DbContext.FetchFirstColumn<int>(sql);
        //    return PopulateEntitiesByEntityIds(ids);
        //}

        public IEnumerable<PersonCorpContract> GetPersonCorpContractsByProjectIds(IEnumerable<int> projectIds)
        {
            if (projectIds == null || projectIds.Count() == 0)
                return Enumerable.Empty<PersonCorpContract>();

            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("person_corp_contract")
                .Where("project_id IN(@0)", projectIds);
            sql.OrderBy("create_date desc");
            var ids = DbContext.FetchFirstColumn<int>(sql);
            return PopulateEntitiesByEntityIds(ids);
        }
    }
}